package com.future.biz;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.future.dao.AreaDAO;
import com.future.dao.InforShareAnswerDAO;
import com.future.dao.InformationDAO;
import com.future.dao.OfficeDAO;
import com.future.dao.OfficeServicesDAO;
import com.future.dao.SecondFillBlankDAO;
import com.future.dao.ShareDepartmentDAO;
import com.future.dbutils.TransactionUtils;
import com.future.model.bo.DepartmentShareInforBO;
import com.future.model.bo.DepartmentSurveyBO;
import com.future.model.bo.OfficeBO;
import com.future.model.bo.ShareInforBO;
import com.future.model.bo.UserBO;
import com.future.model.po.InforShareAnswerModel;
import com.future.model.po.InformationModel;
import com.future.model.po.OfficeModel;
import com.future.model.po.OfficeServicesModel;
import com.future.model.po.SecondFillBlankModel;
import com.future.model.po.ShareDepartmentModel;

/**
 * 第二部分调查表 业务逻辑
 * 
 * @author CrazyCode  petter
 * 
 */

public class DepartmenSurveytBIZ {

	private static Logger logger = LogManager.getLogger(DepartmenSurveytBIZ.class);
	
	/**
	 * 修改第二部分 部门调查（省市县三级政务部门）
	 * @return 返回true  修改或保存成功  返回false  修改或保存失败
	 */
	public boolean updateDepartment(UserBO userBo,SecondFillBlankModel sBlankModel,List<OfficeModel> officeModels,
			List<InforShareAnswerModel> inforShareAnswerModels,List<OfficeServicesModel> officeServicesModels,String[] rowspans){
		boolean para = true;
		boolean flag = true;
		boolean temp = true;
		
		SecondFillBlankDAO secondFillBlankDao = new SecondFillBlankDAO(); 
		InforShareAnswerDAO inforShareAnswerDao = new InforShareAnswerDAO();
		
		boolean secondFillBlankIsfirst = secondFillBlankDao.isOrExist(sBlankModel);
		boolean inforShareAnswerIsfirst = inforShareAnswerDao.isOrExist(userBo.getUser());
		
		
		TransactionUtils.startTransaction(); // 开启事务
		OfficeDAO officeDao  = new OfficeDAO(TransactionUtils.getConnection());
		officeDao.deleteOffice(userBo.getUser());
		int count=0;
		List<Integer> ids = officeDao.saveOffice(officeModels);
		if(rowspans!=null&&rowspans.length>0){
			for (int i = 0; i < rowspans.length; i++) {
				if (rowspans[i]!=null&&!("").equals(rowspans[i])) {
					for (int j = 0; j < (Integer.valueOf(rowspans[i])); j++) {
						if (ids!=null&&ids.size()>0) {
							officeServicesModels.get(count++).setOfficeid(ids.get(i));
						} else {
							officeServicesModels.get(count++).setOfficeid(null);
						}
					}
				}
			}
		}
		count=0;
		OfficeServicesDAO officeServicesDao = new OfficeServicesDAO(TransactionUtils.getConnection());
		if (officeServicesModels!=null&&officeServicesModels.size()>0) {
			for (OfficeServicesModel officeServicesModel : officeServicesModels) {
				para = officeServicesDao.save(officeServicesModel);
				if (!para) {
					break;
				}
			}
		}
		
		flag = this.saveOrupdateSecondFillBlank(sBlankModel,secondFillBlankIsfirst);
		temp = this.saveOrupdateInforShareAnswer(inforShareAnswerModels, inforShareAnswerIsfirst);
		TransactionUtils.commitTransaction(); // 提交事务
		AreaDAO areaDao = new AreaDAO();
		boolean aa = areaDao.updateAreaByCode(userBo.getUser().getUsername());
		
		if (flag&&temp&&para&&aa) {
			return true;
		} else {
			return false;
		}
		
		
	}
	
	
	/**
	 * 保存或修改第二部分 第五大题
	 * @param inforShareAnswerModels
	 * @param inforShareAnswerIsfirst
	 * @return
	 */
	private boolean saveOrupdateInforShareAnswer(List<InforShareAnswerModel> inforShareAnswerModels,
			boolean inforShareAnswerIsfirst){
		boolean temp = false;
		InforShareAnswerDAO inforShareAnswerDao = new InforShareAnswerDAO(TransactionUtils.getConnection());
		if (inforShareAnswerIsfirst) {
			if (inforShareAnswerModels!=null&&inforShareAnswerModels.size()>0) {
				for (InforShareAnswerModel inforShareAnswerModel : inforShareAnswerModels) {
					temp = inforShareAnswerDao.update(inforShareAnswerModel);
					if(!temp)
						break;
				}
			}
		} else {
			if (inforShareAnswerModels!=null&&inforShareAnswerModels.size()>0) {
				for (InforShareAnswerModel inforShareAnswerModel : inforShareAnswerModels) {
					temp = inforShareAnswerDao.save(inforShareAnswerModel);
					if(!temp)
						break;
				}
			}
		}
		return temp;
	}
	
	/**
	 * 保存或修改第二部分填空题
	 * @return
	 */
	private boolean saveOrupdateSecondFillBlank(SecondFillBlankModel sBlankModel,boolean secondFillBlankIsfirst){
		boolean flag = false;
		
		SecondFillBlankDAO secondFillBlankDao = new SecondFillBlankDAO(TransactionUtils.getConnection());
		if (secondFillBlankIsfirst) {
			flag = secondFillBlankDao.update(sBlankModel);
		} else {
			flag = secondFillBlankDao.save(sBlankModel);
		}
		return flag;
	}

	public DepartmentSurveyBO generateSureyByUserId(Integer userId) {
		DepartmentSurveyBO surveyBo = new DepartmentSurveyBO();

		SecondFillBlankDAO secondFillBlankDao = new SecondFillBlankDAO();

		SecondFillBlankModel secondFillBlankModel = null;

		try {
			secondFillBlankModel = secondFillBlankDao.findByUserId(userId);
		} catch (Exception e) {
			secondFillBlankModel = null;
			logger.error(e);
		}
		surveyBo.setSecondFillBlankModel(secondFillBlankModel);
		surveyBo.setDepartmentShareInfoList(generateShareInfoGrid(userId));
		List<OfficeBO> officeBoList = generateOfficeBoGrid(userId);
		surveyBo.setOfficesBoList(officeBoList);

		return surveyBo;
	}

	private List<OfficeBO> generateOfficeBoGrid(Integer userId) {
		List<OfficeBO> result = new ArrayList<OfficeBO>();
		OfficeBO oBo = null;
		OfficeDAO officeDao = new OfficeDAO();
		OfficeModel office = null;

		OfficeServicesDAO officeServicesDao = new OfficeServicesDAO();
		List<OfficeModel> officeModel = officeDao.findByUserId(userId);
		Iterator<OfficeModel> officeIter = officeModel.iterator();
		while (officeIter.hasNext()) {
			office = officeIter.next();
			oBo = new OfficeBO();
			oBo.setOfficeName(office.getOffice());
			oBo.setOfficeId(office.getId());
			List<OfficeServicesModel> officeServicesList = officeServicesDao.findByOfficeId(office.getId());
			oBo.setOffceServiceModelList(officeServicesList);
			result.add(oBo);
		}
		return result;
	}

	private List<DepartmentShareInforBO> generateShareInfoGrid(Integer userId) {
		List<DepartmentShareInforBO> result = new ArrayList<DepartmentShareInforBO>();
		List<ShareInforBO> subResult = null;
		ShareDepartmentModel shareDepartmentModel = null;
		DepartmentShareInforBO departmentShareInforBo = null;
		ShareDepartmentDAO shareDepartmentDao = new ShareDepartmentDAO();
		ShareInforBO shareInforBo = null;
		InformationDAO informationDao = new InformationDAO();
		InformationModel informationModel = null;
		List<ShareDepartmentModel> shareDepartmentList = shareDepartmentDao.findAll();
		Iterator<ShareDepartmentModel> shareDepartmentIter = shareDepartmentList.iterator();

		Map<Integer, InforShareAnswerModel> answerMap = generatInforShareAnswerList(userId);
		boolean flag = false;
		if (answerMap != null) {
			flag = true;
		}

		while (shareDepartmentIter.hasNext()) {
			departmentShareInforBo = new DepartmentShareInforBO();
			shareDepartmentModel = shareDepartmentIter.next();
			departmentShareInforBo.setDepartmentId(shareDepartmentModel.getId());
			departmentShareInforBo.setDepartmentName(shareDepartmentModel.getDepartment());

			List<InformationModel> informationModelList = informationDao.findByDeptId(shareDepartmentModel.getId());
			Iterator<InformationModel> informationModelIter = informationModelList.iterator();

			subResult = new ArrayList<ShareInforBO>();
			while (informationModelIter.hasNext()) {
				informationModel = informationModelIter.next();
				shareInforBo = new ShareInforBO();
				shareInforBo.setInformation(informationModel.getInformation());
				shareInforBo.setInformationId(informationModel.getId());
				InforShareAnswerModel isaModel = answerMap.get(informationModel.getId());
				if (flag && isaModel != null) {
					shareInforBo.setIsShare(isaModel.getIsShare());
					shareInforBo.setShareType(isaModel.getShareType());
				}
				subResult.add(shareInforBo);
			}
			departmentShareInforBo.setDepartmentShareInforList(subResult);
			result.add(departmentShareInforBo);
		}

		return result;
	}

	private Map<Integer, InforShareAnswerModel> generatInforShareAnswerList(Integer userId) {
		InforShareAnswerDAO inforShareAnswerDao = new InforShareAnswerDAO();
		Map<Integer, InforShareAnswerModel> result = new HashMap<Integer, InforShareAnswerModel>();
		List<InforShareAnswerModel> inforShareAnswerList = null;
		try {
			inforShareAnswerList = inforShareAnswerDao.findByUserId(userId);
			Iterator<InforShareAnswerModel> iter = inforShareAnswerList.iterator();
			InforShareAnswerModel model = null;
			while (iter.hasNext()) {
				model = iter.next();
				result.put(model.getInforid(), model);
			}
		} catch (Exception e) {
			logger.error(e);
		}
		return result;
	}
}